#include "stdafx.h"
//-------------------------------------------------------------------------------------------------
//ImageExptLib.cpp  - public interface to ImageExptLib         
//-------------------------------------------------------------------------------------------------
//FreeBSD License
//Copyright 2011 Will Stott All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are
//permitted provided that the following conditions are met:
//
//   1. Redistributions of source code must retain the above copyright notice, this list of
//      conditions and the following disclaimer.
//
//   2. Redistributions in binary form must reproduce the above copyright notice, this list
//      of conditions and the following disclaimer in the documentation and/or other materials
//      provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY Will Stott ``AS IS'' AND ANY EXPRESS OR IMPLIED
//WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Will Stott OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
//ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//The views and conclusions contained in the software and documentation are those of the
//authors and should not be interpreted as representing official policies, either expressed
//or implied, of Will Stott.
//
//----Authors--------------------------------------------------------------------------------------
//created by: will.stott@ucl.ac.uk June 2011
//
//----Comments-------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------

#include <stdlib.h>
#include <stdio.h>

#include "ImageExptLib.h"
#include "TinyXmlLib.h"
#include "ImageExpt.h"

clock_t ImageExptLib::_startTime;

const char * const ImageExptLib::CreateFunctionName = "CreateImageProcStepLib";
const char * const ImageExptLib::ImageFileType = ".bmp";

ImageExptLib::ImageExptLib(void)
{
}


ImageExptLib::~ImageExptLib(void)
{

}

bool ImageExptLib::CreateDefaultImageExptFile(const wchar_t *xmlFile, const char *iefOwner)
{
	bool rc = false;

	wchar_t buff[ImageExptLib::MaxPathFileNameLen];

	const wchar_t *owner = ImageExptLib::ConvertStrTowStr(buff, ImageExptLib::MaxPathFileNameLen, iefOwner, ImageExptLib::MaxPathFileNameLen);	

	ImageExpt *ief = ImageExpt::CreateImageExpt(xmlFile, '\0', owner, L"default", ImageExpt::FromDefaults);
	if (ief != '\0')
	{
		rc = ief->SaveFile();
		delete ief;
		ief = '\0';
	}
	return rc;
}

bool	ImageExptLib::IsFileExist(const wchar_t *pathfilename)
{
	bool rc = false;

	if (pathfilename != '\0')	//no LogMsg() as this is expected to fail often
	{
		size_t len = wcsnlen(pathfilename, ImageExptLib::MaxPathFileNameLen+1 ); 
		if ( (len > 0 ) && (len <= ImageExptLib::MaxPathFileNameLen))
		{
			try
			{
				HANDLE FileExists = ::CreateFileW(pathfilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
				if (FileExists != INVALID_HANDLE_VALUE)
				{
					rc = true;
					CloseHandle(FileExists);
				}
			}
			catch (...)
			{
				rc = false;
			}
		}
	}
	return rc;
}

bool ImageExptLib::CopyImageFile(const wchar_t *dest, const wchar_t *source)
{
	bool rc = false;

	if ((dest == '\0') || (source == '\0'))
		ImageExptLib::LogMsg("ImageExptLib::CopyImageFile", "Error: invalid params dest=%s source=%s", (dest != '\0' ? "not null" : "null"), (source != '\0' ? "not null" : "null"));
	else
	{
		size_t destLen = wcsnlen(dest, ImageExptLib::MaxPathFileNameLen+1 );
		size_t sourceLen = wcsnlen(source, ImageExptLib::MaxPathFileNameLen+1 );

		if ( (destLen <= 0 ) || (destLen > ImageExptLib::MaxPathFileNameLen) || (sourceLen <= 0 ) || (sourceLen > ImageExptLib::MaxPathFileNameLen))
			ImageExptLib::LogMsg("ImageExptLib::CopyImageFile", "Error: invalid params destLen=%d sourceLen=%d", destLen, sourceLen);
		else
		{
			try
			{
				if (::CopyFileW( source, dest, FALSE) == FALSE)
					ImageExptLib::LogMsg("ImageExptLib::CopyImageFile", "Error: ::CopyFile() failed, GetLastError()=%d", GetLastError());
				else
					rc = true;
			}
			catch (...)
			{
				ImageExptLib::LogMsg("ImageExptLib::CopyImageFile", "unexpected exception");
				rc = false;
			}
		}
	}
	return rc;
}


bool ImageExptLib::DeleteImageFile(const wchar_t *pathfilename)
{
	bool rc = false;

	if (pathfilename == '\0') 
		ImageExptLib::LogMsg("ImageExptLib::DeleteImageFile", "Error: invalid param (null)");
	else
	{
		size_t sourceLen = wcsnlen(pathfilename, ImageExptLib::MaxPathFileNameLen+1 );

		if ( (sourceLen <= 0 ) || (sourceLen > ImageExptLib::MaxPathFileNameLen))
			ImageExptLib::LogMsg("ImageExptLib::DeleteImageFile", "Error: invalid param strlen=%d ", sourceLen);
		else
		{
			try
			{
				if (::DeleteFileW(pathfilename) == FALSE)
					ImageExptLib::LogMsg("ImageExptLib::DeleteImageFile", "Error: ::CopyFile() failed, GetLastError()=%d", GetLastError());
				else
					rc = true;
			}
			catch (...)
			{
				ImageExptLib::LogMsg("ImageExptLib::DeleteImageFile", "unexpected exception");
				rc = false;
			}
		}
	}
	return rc;
}

const char *ImageExptLib::ConvertwStrToStr(char  *dest, size_t destBuffCharsLen, const wchar_t *source, size_t sourcewStrLenMax)
{
	const char *rc = '\0';

	if ((dest != '\0') && (source != '\0') && (destBuffCharsLen > 0) && (sourcewStrLenMax > 0))
	{
		size_t   convertCnt = 0;
		size_t   sourceCnt = wcsnlen(source, sourcewStrLenMax+1 ) + 1;		//if source is not terminated or is longer than sourcewStrLenMax, then wcsnlen returns sourcewStrLenMax+1 so convertCnt != sourceCnt

		if ( (wcstombs_s(&convertCnt, dest, destBuffCharsLen, source, sourcewStrLenMax ) != 0) || (convertCnt != sourceCnt))
			ImageExptLib::LogMsg("ImageExptLib::ConvertwStrToStr", "Error: %d chars of %d converted", convertCnt, sourceCnt);
		else
			rc = dest;
	}
	return rc;
}

const wchar_t	  *ImageExptLib::ConvertStrTowStr(wchar_t *dest, size_t destBuffwCharsLen, const char *source, size_t sourceStrLenMax)
{
	const wchar_t *rc = '\0';

	if ((dest != '\0') && (source != '\0') && (destBuffwCharsLen > 0) && (sourceStrLenMax > 0))
	{
		size_t   convertCnt = 0;
		size_t   sourceCnt = strnlen(source, sourceStrLenMax+1 ) + 1;	//if source is not terminated or is longer than sourceStrLenMax, then strnlen returns sourcewStrLenMax+1 so convertCnt != sourceCnt

		if ( (mbstowcs_s(&convertCnt, dest, destBuffwCharsLen, source, sourceStrLenMax) != 0 ) || (convertCnt != sourceCnt))
			ImageExptLib::LogMsg("ImageExptLib::ConvertStrTowStr", "Error: %d chars of %d converted from %s", convertCnt, sourceCnt, source);	
		else
			rc = dest;
	}
	return rc;
}


void ImageExptLib::LogMsg(const char *method, const char *printfStr, ...)
{
#pragma warning(disable:4996)		//_snprintf is depreciated

	char	buffer[ImageExptLib::DebugStringLen];

	clock_t now = clock();
	double ticks = (double)(now - _startTime) / CLOCKS_PER_SEC;

	int len = 0;
	int lenPreamble = 0;
	if (printfStr == '\0')
		len = _snprintf(buffer, sizeof(buffer), "[%7.3f] %s: (!!!format string was null!!!)", ticks, method);
	else
	{
		va_list argptr;
		va_start( argptr, printfStr );

		lenPreamble = _snprintf(buffer, sizeof(buffer), "[%7.3f] %s: ", ticks, method);
		if ( (lenPreamble >= sizeof(buffer)) || (lenPreamble < 0) )
			len = lenPreamble;
		else
		{
			int lenFormat = vsnprintf(&buffer[lenPreamble], ImageExptLib::DebugStringLen-lenPreamble, printfStr, argptr);
			if ( lenFormat <= 0 )
				len = sizeof(buffer);
			else
				len = lenPreamble + lenFormat;
		}
		va_end( argptr );
	}
	if ((len < (sizeof(buffer)-1)) && (len >= 0))
	{
		buffer[len] = '\n';
		buffer[len+1] = '\0';
	}
	else
	{
		buffer[sizeof(buffer)-5] = '.';
		buffer[sizeof(buffer)-4] = '.';
		buffer[sizeof(buffer)-3] = '.';
		buffer[sizeof(buffer)-2] = '\n';
		buffer[sizeof(buffer)-1] = '\0';
	}
	::OutputDebugString(buffer);

#pragma warning(default:4996)
}



//-------------------------------------------------------------------------------------------------
//			E N D   O F   F I L E
//-------------------------------------------------------------------------------------------------


